<template>
	<!--  班次 -->
	<div class="content">
		<div class="pageSearchView">
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<el-form-item label="班次名称">
					<el-input v-model="searchParam.name" placeholder="请输入班次名称" clearable style="width: 200px" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
					<el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">列表信息</div>
				<div class="pageTableButView">
					<el-button :icon="Plus" @click="handleAdd()">新建</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
				<el-table-column label="序号" align="center" width="70">
					<template #default="scope">
						<!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{ (pageSearch.current - 1) * pageSearch.pageSize +
					scope.$index + 1 }}
					</template>
				</el-table-column>
				<el-table-column prop="name" label="班次名称" align="center" width="250" />
				<el-table-column prop="userName" label="起始时间和结束时间" align="center" min-width="250">
					<template #default="scope">
						<div v-for="(shift, index) in parsedShiftJson(scope.row.shiftJson)" :key="index">
							<span>{{ shift.startTime }} - {{ shift.endTime }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="description" label="班组描述" align="center" width="300" />
				<el-table-column label="操作" align="center" fixed="right" width="200">
					<template #default="scope">
						<el-button @click="handleEdit(scope.row)" type="text" size="small" plain :icon="Edit">编辑</el-button>
						<el-button @click="handleDel(scope.row)" text type="danger" size="small" :icon="Delete">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
											 :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
											 :total="pageTotal"
											 @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 弹窗表单 -->
		<el-dialog v-model="showCrud" :title="crudTitle" width="1000">
			<el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
				<el-row :gutter="10">
					<el-col :span="12">
						<el-form-item required label="班次名称" prop="name">
							<el-input v-model="formData.name" placeholder="请输入班次名称" clearable style="width:100% "></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="班次描述">
							<el-input type="textarea" v-model="formData.description" placeholder="请输入班组描述" clearable
												style="width:100% "></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="10" v-for="(item, index) in formData.shiftJson" :key="index"
								style="display: flex;align-items: center;padding: 10px 0 10px 20px;">
					<el-col :span="4">
						<el-select v-model="item.shiftName" placeholder="名称" clearable style="width: 90%;">
							<el-option v-for="item in classOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-col>
					<el-col :span="5">
						<el-time-picker
							v-model="item.startTime"
							placeholder="开始时间"
							value-format="HH:mm"
							style="width: 100%;"
						/>
					</el-col>
					<el-col :span="5">
						<el-time-picker
							v-model="item.endTime"
							placeholder="结束时间"
							value-format="HH:mm"
							style="width: 100%;"
						/>
					</el-col>
					<el-col :span="6"> 休息时长：
						<el-input v-model="item.restTime" type="number" style="width:60%;">
							<template #append>min</template>
						</el-input>
					</el-col>
					<el-col :span="3">
						<el-button :icon="Plus" text size="small" style="margin-left: 10px" @click="addClassList"
											 v-if="index == 0">添加班次
						</el-button>
						<el-button :icon="Delete" text type="danger" size="small" style="margin-left: 10px"
											 @click="delClassList(index)" v-else>删除班次
						</el-button>
					</el-col>
				</el-row>
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useEquipmentData } from '@/hooks/baseData/equipment';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Search, Share, Upload, Refresh, Plus, DocumentCopy } from '@element-plus/icons-vue';

const pageSearch = ref({
	current: 1,
	pageSize: 10
});

const configTableShow = ref(false);

const handleClick = (e) => {
	console.log(e, 'handleClick');
};

const rowInfo = ref({});

const workOrderList = ref({});

const showMaterial = ref(false);

const workDetailData = ref([{
	code: '1code89980',
	name: '测试name',
	qualityType: 'qualityType'
}]);

const pageTotal = ref(null); // 页面总数
const isEdit = ref(false); // 是否编辑
const showCrud = ref(false); // 编辑/新建弹框
const searchParam = ref({}); // 页面检索条件
const showConfig = ref(false);
const configData = ref({});
const crudTitle = computed(() => {
	return isEdit.value ? '编辑' : '新建';
}); // 弹出层标题

import type { ComponentSize, FormInstance, FormRules } from 'element-plus';

const ruleFormRef = ref<FormInstance>();

interface RuleForm {
	name: string;
	description: string;
	shiftJson: Array<{
		shiftName: string;
		startTime: string;
		endTime: string;
		restTime: number;
	}>;
}

const originalFormData = reactive<RuleForm>({
	name: '',
	description: '',
	shiftJson: [{} as any]
});

let formData = reactive<RuleForm>(originalFormData);

const rules = reactive<FormRules<RuleForm>>({
	name: [
		{ required: true, message: '请输入班次名称', trigger: 'blur' }
	]
});

const paginatedData = ref<RuleForm[]>([]);

const materiaList = ref([]); // 物料表
const userList = ref([]); // 人员
const workRoomList = ref([]); // 车间
const procedureOrderList = ref([]); // 工序订单
const classOptions = ref([
	{
		label: '早班',
		value: '0'
	}, {
		label: '中班',
		value: '1'
	}, {
		label: '晚班',
		value: '2'
	}
]);

const parsedShiftJson = (jsonString: any) => {
	try {
		return JSON.parse(jsonString);
	} catch (error) {
		console.error('JSON解析错误:', error);
		return [];
	}
};

const getOption = () => {
	// axiosInstance.post('/api/userPerson/getAll', {})
	//   .then(res => {
	//     if (res.code !== 200) {
	//       ElMessage.error(res.message);
	//       return false;
	//     }
	//     userList.value = res.data;
	//   });

	axiosInstance.post('/api/basedataOrganization/getAll', {})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			workRoomList.value = res.data;
		});
};

// 获取列表接口
const getList = () => {
	axiosInstance.post('/api/swingShift/getPage', {
		...searchParam.value,
		...pageSearch.value
	})
		.then(res => {
			if (res.code !== 200) {
				ElMessage.error(res.message);
				return false;
			}
			paginatedData.value = res.data.records;
			pageTotal.value = res.data.total;
		});
};

const handleSizeChange = (e) => {
	pageSearch.value.pageSize = e;
	getList();
};

const handleCurrentChange = (e) => {
	pageSearch.value.current = e;
	getList();
};

// 重置搜索条件
const resetSearch = () => {
	searchParam.value = {};
	pageSearch.value.current = 1;
	getList();
};

const addClassList = () => {
	formData.shiftJson.push({} as any);
};

const delClassList = (index) => {
	formData.shiftJson.splice(index, 1);
};

// 点击新建
const handleAdd = () => {
	isEdit.value = false;
	formData = reactive({
		shiftJson: [{} as any]
	});
	showCrud.value = true;
};

// 编辑
const handleEdit = (row: any) => {
	isEdit.value = true;
	formData = reactive({
		...row,
		shiftJson: JSON.parse(row.shiftJson)
	});
	showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		axiosInstance.delete(`/api/swingShift/delete`, {
			data: {
				ids: [row.id]
			}
		}).then(res => {
			if (res.code === 200) {
				ElMessage.success('删除成功');
				getList(); // 刷新数据
			}
		});
	});
};

// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
	if (!e) return;
	await e.validate((valid, fields) => {
		if (valid) {
			const params = {
				...formData,
				shiftJson: formData.shiftJson.map(item => {
					return {
						...item,
						startTime: item.startTime,
						endTime: item.endTime
					};
				})
			};
			const paramsJson = { ...params, shiftJson: JSON.stringify(params.shiftJson) };
			console.log({ ...params, shiftJson: params.shiftJson }, 'params');

			if (isEdit.value) {
				// 编辑
				axiosInstance.put('/api/swingShift/update', paramsJson).then(res => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('操作成功!');
					showCrud.value = false;
					getList(); // 刷新数据
				});
			} else {
				// 新建
				axiosInstance.post('/api/swingShift/save', paramsJson).then(res => {
					if (res.code !== 200) {
						ElMessage.error(res.message);
						return false;
					}
					ElMessage.success('操作成功!');
					showCrud.value = false;
					getList(); // 刷新数据
				});
			}
		}
	});
};

onMounted(() => {
	getList();
	getOption();
});
</script>
<style scoped>
.content {
}
</style>